<template>
  <div class="evaluation-list">
    <el-card class="list-header">
      <div class="header-content">
        <div class="title-section">
          <el-button @click="goBack" icon="ArrowLeft" type="text" class="back-button">
            返回仪表板
          </el-button>
          <h1 class="page-title">评价分析列表</h1>
          <p class="page-subtitle">查看所有评价分析记录</p>
        </div>
        <div class="action-section">
          <el-button type="primary" @click="batchAnalyze" :loading="batchLoading">
            <el-icon><MagicStick /></el-icon>
            批量分析
          </el-button>
          <el-button @click="refreshList" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 筛选条件 -->
    <el-card class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="司机ID">
          <el-input v-model="filterForm.driverId" placeholder="请输入司机ID" clearable />
        </el-form-item>
        <el-form-item label="评分范围">
          <el-select v-model="filterForm.ratingRange" placeholder="选择评分范围" clearable>
            <el-option label="全部评分" value="" />
            <el-option label="5星 (评分: 5)" value="5" />
            <el-option label="4星 (评分: 4)" value="4" />
            <el-option label="3星 (评分: 3)" value="3" />
            <el-option label="2星 (评分: 2)" value="2" />
            <el-option label="1星 (评分: 1)" value="1" />
            <el-option label="高评分 (评分: 4-5星)" value="high" />
            <el-option label="中评分 (评分: 3星)" value="medium" />
            <el-option label="低评分 (评分: 1-2星)" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="分析时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="applyFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 筛选结果统计 -->
      <div v-if="analysisList.length > 0" class="filter-stats">
        <el-tag type="info">共找到 {{ pagination.total }} 条记录</el-tag>
        <el-tag v-if="filterForm.ratingRange" type="success">
          评分范围: {{ getRatingRangeText(filterForm.ratingRange) }}
        </el-tag>
        <el-tag v-if="filterForm.driverId" type="warning">
          司机ID: {{ filterForm.driverId }}
        </el-tag>
        <el-tag v-if="filterForm.dateRange && filterForm.dateRange.length === 2" type="primary">
          时间范围: {{ filterForm.dateRange[0] }} 至 {{ filterForm.dateRange[1] }}
        </el-tag>
      </div>
    </el-card>

    <!-- 分析列表 -->
    <el-card class="list-content">
      <el-table
        :data="analysisList"
        style="width: 100%"
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="订单号" width="120">
          <template #default="scope">
            {{ scope.row.order_rating?.order?.order_number || 'N/A' }}
          </template>
        </el-table-column>
        <el-table-column label="司机ID" width="100">
          <template #default="scope">
            {{ scope.row.order_rating?.driver_id || 'N/A' }}
          </template>
        </el-table-column>
        <el-table-column label="乘客ID" width="100">
          <template #default="scope">
            {{ scope.row.order_rating?.passenger_id || 'N/A' }}
          </template>
        </el-table-column>
        <el-table-column label="评分" width="120">
          <template #default="scope">
            <div class="rating-display">
              <el-rate v-model="scope.row.order_rating.rating" disabled show-score />
              <span class="rating-text">(评分: {{ scope.row.order_rating.rating }})</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评价内容" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.order_rating?.comment || '暂无评价内容' }}
          </template>
        </el-table-column>
        <el-table-column label="分析结果" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.analysis_result || '暂无分析结果' }}
          </template>
        </el-table-column>
        <el-table-column label="分析时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.analysis_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewDetail(scope.row)">
              查看详情
            </el-button>
            <el-button type="success" size="small" @click="viewSuggestions(scope.row)">
              改进建议
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 批量分析对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量分析" width="500px">
      <div class="batch-analyze-content">
        <p>已选择 {{ selectedItems.length }} 条评价记录进行批量分析</p>
        <el-table :data="selectedItems" style="width: 100%" max-height="300">
          <el-table-column label="订单号" width="120">
            <template #default="scope">
              {{ scope.row.order_rating?.order?.order_number || 'N/A' }}
            </template>
          </el-table-column>
          <el-table-column label="司机ID" width="100">
            <template #default="scope">
              {{ scope.row.order_rating?.driver_id || 'N/A' }}
            </template>
          </el-table-column>
          <el-table-column label="评分" width="80">
            <template #default="scope">
              <el-rate v-model="scope.row.order_rating.rating" disabled />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBatchAnalyze" :loading="batchAnalyzeLoading">
            确认分析
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, MagicStick, ArrowLeft } from '@element-plus/icons-vue'
import { evaluationAPI } from '@/api/evaluation'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableLoading = ref(false)
const batchLoading = ref(false)
const batchAnalyzeLoading = ref(false)
const batchDialogVisible = ref(false)
const analysisList = ref([])
const selectedItems = ref([])

// 筛选表单
const filterForm = ref({
  driverId: '',
  ratingRange: '',
  dateRange: []
})

// 分页
const pagination = ref({
  page: 1,
  pageSize: 20,
  total: 0
})

// 初始化页面
onMounted(() => {
  loadAnalysisList()
})

// 加载分析列表
async function loadAnalysisList() {
  tableLoading.value = true
  try {
    const params = {
      page: pagination.value.page,
      page_size: pagination.value.pageSize
    }

    // 添加筛选条件
    if (filterForm.value.driverId) {
      params.driver_id = filterForm.value.driverId
    }
    if (filterForm.value.ratingRange) {
      // 处理评分范围
      if (filterForm.value.ratingRange === 'high') {
        // 高评分(4-5星) - 需要特殊处理，前端先获取所有数据再筛选
        params.rating_min = 4
        params.rating_max = 5
      } else if (filterForm.value.ratingRange === 'medium') {
        // 中评分(3星)
        params.rating = 3
      } else if (filterForm.value.ratingRange === 'low') {
        // 低评分(1-2星) - 需要特殊处理
        params.rating_min = 1
        params.rating_max = 2
      } else {
        // 具体星级
        params.rating = filterForm.value.ratingRange
      }
    }
    if (filterForm.value.dateRange && filterForm.value.dateRange.length === 2) {
      params.start_date = filterForm.value.dateRange[0]
      params.end_date = filterForm.value.dateRange[1]
    }

    const response = await evaluationAPI.getEvaluationAnalysisList(params)
    console.log('分析列表API响应:', response)
    if (response.data) {
      analysisList.value = response.data.data || []
      pagination.value.total = response.data.total || 0
      console.log('分析列表数据:', analysisList.value)
      if (analysisList.value.length > 0) {
        console.log('第一条记录:', analysisList.value[0])
        console.log('订单信息:', analysisList.value[0].order_rating?.order)
      }
    }
  } catch (error) {
    console.error('加载分析列表失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 应用筛选
function applyFilter() {
  pagination.value.page = 1
  loadAnalysisList()
}

// 重置筛选
function resetFilter() {
  filterForm.value = {
    driverId: '',
    ratingRange: '',
    dateRange: []
  }
  pagination.value.page = 1
  loadAnalysisList()
}

// 刷新列表
async function refreshList() {
  loading.value = true
  await loadAnalysisList()
  ElMessage.success('数据已刷新')
  loading.value = false
}

// 处理选择变化
function handleSelectionChange(selection) {
  selectedItems.value = selection
}

// 批量分析
function batchAnalyze() {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择要分析的记录')
    return
  }
  batchDialogVisible.value = true
}

// 确认批量分析
async function confirmBatchAnalyze() {
  batchAnalyzeLoading.value = true
  try {
    const orderRatingIds = selectedItems.value.map(item => item.order_rating.id)
    const response = await evaluationAPI.batchAnalyzeEvaluation(orderRatingIds)
    
    if (response.data && response.data.success) {
      ElMessage.success(`成功分析 ${orderRatingIds.length} 条记录`)
      batchDialogVisible.value = false
      selectedItems.value = []
      await loadAnalysisList()
    } else {
      ElMessage.error(response.data?.error || '批量分析失败')
    }
  } catch (error) {
    console.error('批量分析失败:', error)
    ElMessage.error('批量分析失败')
  } finally {
    batchAnalyzeLoading.value = false
  }
}

// 返回仪表板
function goBack() {
  router.push('/evaluation/dashboard')
}

// 查看详情
function viewDetail(row) {
  router.push(`/evaluation/detail/${row.id}`)
}

// 查看改进建议
function viewSuggestions(row) {
  router.push(`/evaluation/suggestions?analysis_id=${row.id}`)
}

// 分页处理
function handleSizeChange(size) {
  pagination.value.pageSize = size
  pagination.value.page = 1
  loadAnalysisList()
}

function handleCurrentChange(page) {
  pagination.value.page = page
  loadAnalysisList()
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取评分范围文本
function getRatingRangeText(range) {
  switch (range) {
    case 'high':
      return '4-5星 (评分: 4-5)'
    case 'medium':
      return '3星 (评分: 3)'
    case 'low':
      return '1-2星 (评分: 1-2)'
    case '5':
      return '5星 (评分: 5)'
    case '4':
      return '4星 (评分: 4)'
    case '3':
      return '3星 (评分: 3)'
    case '2':
      return '2星 (评分: 2)'
    case '1':
      return '1星 (评分: 1)'
    default:
      return '全部评分'
  }
}
</script>

<style scoped>
.evaluation-list {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.list-header {
  margin-bottom: 20px;
  border-radius: 12px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
}

.back-button {
  margin-bottom: 8px;
  color: #409EFF;
  font-size: 14px;
  padding: 0;
}

.back-button:hover {
  color: #66b1ff;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.action-section {
  display: flex;
  gap: 12px;
}

.filter-section {
  margin-bottom: 20px;
  border-radius: 12px;
}

.list-content {
  border-radius: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.batch-analyze-content {
  max-height: 400px;
  overflow-y: auto;
}

.batch-analyze-content p {
  margin-bottom: 16px;
  color: #606266;
}

.filter-stats {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  font-size: 14px;
  color: #606266;
}

.rating-display {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rating-text {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .action-section {
    justify-content: center;
  }
  
  .el-form--inline .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }
}
</style> 